package com.company.ThreadDemo;

// 生产者 消费者  缓冲区 产品
public class PCDemo {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Productor(synContainer).start();
        new Consumer(synContainer).start();
    }
}

//生产者
class Productor extends Thread{
    SynContainer synContainer;
    public Productor(SynContainer synContainer){
        this.synContainer = synContainer;
    }
    @Override
    public void run(){
        for (int i = 0; i < 100; i++) {
            System.out.println("生产第"+i+"只鸡");
            try {
                synContainer.push(new Chicken(i));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//消费者
class Consumer extends Thread{
    SynContainer synContainer;
    public Consumer(SynContainer synContainer){
        this.synContainer = synContainer;
    }
    @Override
    public void run(){
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第"+i+"只鸡");
            try {
                synContainer.pop();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//产品
class Chicken{
    int id;
    public Chicken(int id){
        this.id = id;
    }

}
//缓冲区
class SynContainer{
    private Chicken[] chickens = new Chicken[10];
    int count = 0;
    public synchronized void push(Chicken chicken) throws InterruptedException {
        if(count==10){
            this.wait();
        }
        chickens[count] = chicken;
        count++;
        this.notifyAll();
    }
    public synchronized Chicken pop() throws InterruptedException {
        if(count==0){
            this.wait();
        }
        count--;
        Chicken chicken = chickens[count];

        this.notifyAll();
        return chicken;
    }
}